package com.concurrence;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.client.RepChainJksClient;
import com.google.protobuf.util.JsonFormat;
import com.protos.Peer;
import org.apache.commons.codec.binary.Hex;

import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;

/**
 * 注册账户
 */
public class SignUpSigner extends Thread {

    // 账户管理合约ID
    private Peer.ChaincodeId contractCertId = Peer.ChaincodeId.newBuilder().setChaincodeName("ContractCert").setVersion(1).build();
    // 账户列表
    private ArrayList creditCodeList = new ArrayList();
    // 各个节点的账户地址
    private String[] node_addr = {"121000005l35120456", "12110107bi45jh675g", "122000002n00123567", "921000005k36123789", "921000006e0012v696"};

    // 账户列表初始化
    {
        for (int i = 0; i < 100; i++) {
            String creditCode = UUID.randomUUID().toString().replace("-", "");
            creditCodeList.add(creditCode);
        }
    }

    /**
     * 批量注册100个账户
     */
    @Override
    public void run() {
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            signUpSigner(random.nextInt(4), i);
        }
    }

    /**
     * 注册账户，creditCode由UUID生成
     * 随机选择管理员来进行注册账户
     */
    private void signUpSigner(int i, int j) {

        RepChainJksClient adminClient = new RepChainJksClient(
                "localhost:8081",
                "jks/" + node_addr[i] + ".node" + (i + 1) + ".jks", "123",
                node_addr[i] + ".node" + (i + 1));
        // 管理员证书ID
        Peer.CertId adminCertId = Peer.CertId.newBuilder().setCreditCode(node_addr[i]).setCertName("node" + (i + 1)).build();

        // 注册账户
        ArrayList<String> certNames = new ArrayList<>();
        certNames.add("certName_1");
        certNames.add("certName_2");
        // 用uuid生成一个账户地址
//        String creditCode = UUID.randomUUID().toString().replace("-", "");
        // 可以自己构造一个javaBean，然后使用Json序列化
        Peer.Signer signer = Peer.Signer.newBuilder()
                .setName("signerName")
                .setCreditCode((String) creditCodeList.get(j))
                .setMobile("13812345678")
                .addAllCertNames(certNames)
                .build();
//        creditCodeList.add(creditCode);
        Peer.Transaction signUpSignerTxr = Peer.Transaction.getDefaultInstance();
        try {
            signUpSignerTxr = adminClient.createTransactionForInvoke(adminCertId, contractCertId, "SignUpSigner", JsonFormat.printer().print(signer));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        String signUpSignerTxrStr = Hex.encodeHexString(signUpSignerTxr.toByteArray());
        JSONObject signUpSignerTxrResult = adminClient.postTranByString(JSON.toJSONString(signUpSignerTxrStr));
        System.out.println(Thread.currentThread().getName() + ": signUpSigner: " + signUpSignerTxrResult);
    }

    public ArrayList getCreditCodeList() {
        return creditCodeList;
    }
}
